<?php

namespace apps\marriage\app\op\controller;

use apps\marriage\core\service\UserService;
use apps\marriage\core\service\VipCardNoService;
use apps\marriage\core\service\VipCardService;
use think\Request;

class VipCardNoController extends BaseMarriageOpController
{
    /**
     * @var VipCardService
     */
    private $vipCardService;

    /**
     * @var VipCardNoService
     */
    private $vipCardNoService;

    /**
     * @var UserService
     */
    private $userService;

    protected function init()
    {
        parent::init();
        $this->vipCardService = service('VipCard', SERVICE_NAMESPACE);
        $this->vipCardNoService = service('VipCardNo', SERVICE_NAMESPACE);
        $this->userService = service('User', SERVICE_NAMESPACE);
    }

    public function lists(Request $request)
    {
        $pageSize = $request->param('page_size', 10, 'intval');
        $vipCardId = $request->param('vip_card_id', 0, 'intval');
        $params = [
            'vip_card_id' => $vipCardId
        ];
        $sortOrder = [
            'active_time' => 'DESC'
        ];
        $res = $this->vipCardNoService->pageListByParams($params, $pageSize, [], $sortOrder);
        foreach ($res['data'] as &$rs) {
            $vipCard = $this->vipCardService->getByPk($rs['vip_card_id']);
            $vipCard = $this->vipCardService->format($vipCard);
            $rs['vip_card'] = $vipCard;
            if($rs['owner_uid'] > 0) {
                $rs['owner'] = $this->userService->getByPk($rs['owner_uid']);
                $rs['owner'] = arrayOnly($rs['owner'], ['id', 'nick', 'avatar_url']);
            } else {
                $rs['owner'] = null;
            }
        }
        return $this->success($res);
    }

    public function generate(Request $request)
    {
        $vipCardId = $request->param('vip_card_id', 0, 'intval');
        $amount = $request->param('amount', 0, 'intval');
        $this->vipCardNoService->onGenerate($vipCardId, $amount);
        return $this->success();
    }

    public function export(Request $request)
    {
        $vipCardId = $request->param('vip_card_id', 0, 'intval');
        $noList = $this->vipCardNoService->getAll([
            'vip_card_id' => $vipCardId,
            'owner_uid' => 0
        ]);
        $cardNoList = [];
        foreach ($noList as $item) {
//            $cardNoList[] = [$item['no'], $item['password']];
            $no = (string) $item['no'];
            $no = substr($no, 0, 4) . '-' . substr($no, 4, 4)
                . '-' . substr($no, 8, 4) . '-' . substr($no, 12);
            $cardNoList[] = [$no];
        }

//        $headers = ['number', 'password'];
//        $headers = ['number'];
        $headers = [];
        $fileData = $this->toCSV($cardNoList, $headers, true);

        // 头信息设置
        header("Content-type:text/csv");
        header("Content-Disposition:attachment;filename=" . '会员卡号-' . date('YmdHi') . '.csv');
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
        header('Expires:0');
        header('Pragma:public');
        echo $fileData;
    }

    private function toCSV(array $data, array $headers = array(), $asString = false) {
        $stream = ($asString)
            ? fopen("php://temp/maxmemory", "w+")
            : fopen("php://output", "w");

        if (!empty($headers)) {
            fputcsv($stream, $headers);
        }

        foreach ($data as $record) {
            fputcsv($stream, $record);
        }

        if ($asString) {
            rewind($stream);
            $returnVal = stream_get_contents($stream);
            fclose($stream);
            return $returnVal;
        }
        else {
            fclose($stream);
        }
    }
}